<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Portal extends CI_Controller
{
	private $user_id;
	function __construct()
	{
		parent::__construct();
		
		$this->load->config();
		$this->load->config('layout', TRUE);
		$this->load->helper(array('form', 'url'));
		$this->load->library('security');
		$this->load->library('session');
		$this->load->library('tank_auth');
		$this->load->model('activity_model');
		$this->user_id = $this->session->userdata('user_id');
	}
	

	function index()
	{
		$data = $this->session->all_userdata();
		$data['search_feature'] = $this->load->view('coplay/portal/search_feature', '', true);
		$this->load->view('coplay/header', $data);
		$this->load->view('coplay/portal/activity_flow', $data);
		
	}
	
	function get_not_login_form(){
		return $this->load->view('stareit/not_login_yet', '' ,true);
	}
	
	function get_login_form(&$session_data){
		$data = array();
		$data['profile_picture'] = $this->config->item('fb_graph_api_url', 'stareit').$session_data['user_data']['LOGIN_INFO']['id'].'/picture';
		$data['user_name'] = $session_data['user_data']['LOGIN_INFO']['name'];
		return $this->load->view('stareit/login_already', $data ,true);
	}
	
	function get_site_features(){
		return $this->load->view('stareit/site_features','',true);
	}
	
	function get_categories(){
		$user_data = $this->session->userdata('user_data');//get session
		if(!isset($user_data['LOGIN_INFO']['id'])){ // not login yet
			$data['categories'] = $this->config->item('sub_category', 'rss');
			echo $this->load->view('stareit/category_nav', $data ,true);
		}
		else{
			$uncategorize = '未分類';
			$data['categories'] = $user_data['CATEGORY_DATA']; // user customize categories
			/*
			 * 把未分類移至array 最後方
			 */
			$temp = $data['categories'][$uncategorize];
			unset($data['categories'][$uncategorize]);
			$data['categories'][$uncategorize] = $temp;
			//echo "<pre>";print_r($data);echo "</pre>";
			echo $this->load->view('stareit/category_nav', $data ,true);
		}
	}
	
	function get_category_form(){ //deprecated
		$user_data = $this->session->userdata('user_data');//get session
		$data = array();
		if(!isset($user_data['LOGIN_INFO']['id'])){ // not login yet
			$data['categories'] = $this->config->item('sub_category', 'rss');
			//echo "<pre>";print_r($data);echo "</pre>";
			echo $this->load->view('stareit/category_form', $data ,true);
		}
		else{
			$uncategorize = '未分類';
			$data['categories'] = $user_data['CATEGORY_DATA']; // user customize categories
			/*
			 * 把未分類移至array 最後方
			 */
			$temp = $data['categories'][$uncategorize];
			unset($data['categories'][$uncategorize]);
			$data['categories'][$uncategorize] = $temp;
			//echo "<pre>";print_r($data);echo "</pre>";
			echo $this->load->view('stareit/category_form', $data ,true);
		} 
	}
	
	function get_hot_searches(){
		$user_data = $this->session->userdata('user_data');//get session
		$data = array();
		
		$data['hot_searches'] = $this->googleapi->getTopSearchKeywords();
		//var_dump($search_keywords);
		//echo "<pre>";print_r($data);echo "</pre>";
		
		echo json_encode(array('status'=>true,'msg'=>$this->load->view('stareit/hot_searches', $data ,true),'next_page'=>''));
	}
	
	function get_blog_results(){
		$post_data = $this->input->post(NULL, TRUE); // returns all POST items with XSS filter
		$this->load->library('googleapi');
		$json = $this->googleapi->getBlogResults($post_data['start'],$post_data['q']);
		
        $next_start = '';
        $previous_start = '';
        $currentPageIndex = @$json->responseData->cursor->currentPageIndex;
        
        if (isset($json->responseData->cursor->pages[$currentPageIndex + 1])) {
            $next_start = @$json->responseData->cursor->pages[$currentPageIndex + 1]->start;
        
        }
        
        if (isset($json->responseData->cursor->pages[$currentPageIndex - 1])) {
            $previous_start = @$json->responseData->cursor->pages[$currentPageIndex - 1]->start;
        }
        
        
        $results = @$json->responseData->results;
        //echo "<pre>";print_r($results);echo "</pre>";
		$msg = '';
		/*
		 * get search ads
		 */ 
		 /*
		$msg .= '<div class="content">'; 
			$msg .= $this->get_ads_search_result();
		$msg .= '</div>';
		*/
		
        foreach (@$results as $key=>$data) {
        	$msg .= '<div class="content">';
            $msg .= '<h2><a href="'.$data->postUrl.'" target="_blank">'.$data->title.'</a></h2>';
            $msg .= '<p>'.strip_tags($data->content).'</p>';
			$msg .= '</div>';
        }
       
		if ($next_start != '') {	
			$next_page = '<a href="javascript:;" onclick="searchFeed(\''.$next_start.'\',\''.$post_data['q'].'\')" id="next">more</a>';
		}
		else{
			$next_page = '';
		}
		
		echo json_encode(array('msg'=>$msg,'next_page'=>$next_page));
	}
	
	function get_more_feed(){
		$data = $this->input->post(NULL, TRUE); // returns all POST items with XSS filter
		$data['url'] = explode('|',$data['url']);
		echo $this->get_content($data['url'],$data['offset'],true);
	}
	
	function change_feed_source(){
		$url = array();
		$urlMappingTitle = array();
		$data = $this->input->post(NULL, TRUE); // returns all POST items with XSS filter
        $this->mappingdata->get_mapping_data();
        $user_data = $this->session->userdata('user_data');//get session
        //echo "<pre>";print_r($user_data);echo "</pre>";
        if (isset($user_data['CATEGORY_DATA'][$data['category']]) && !empty($user_data['CATEGORY_DATA'][$data['category']])) {
            foreach ($user_data['CATEGORY_DATA'][$data['category']] as $key=>$feed) {
                if(isset($feed['url'])){
						$url[] = $feed['url'];	
					}
            }
            echo $this->get_content($url, '', true);
        }
		elseif($data['category'] == 'all'){ // get all rss, order by date time
		//echo "<pre>";print_r($user_data['CATEGORY_DATA']);echo "</pre>";
			foreach($user_data['CATEGORY_DATA'] as $cat=>$cat_obj){
				foreach($cat_obj as $key=>$feed){
					if(isset($feed['url'])){
						$url[] = $feed['url'];	
					}
				}
			}
			//echo "<pre>";print_r($url);echo "</pre>";
            echo $this->get_content($url, '', true);
		} 
        else {
            echo json_encode(array('status'=>false, 'msg'=>'此分類尚無內容', 'next_page'=>''));
        }

	}
	
	function change_feed_source_by_url(){
		$url = array();
		$urlMappingTitle = array();
		$data = $this->input->post(NULL, TRUE); // returns all POST items with XSS filter
		echo $this->get_content($data['url'], '', true);
		/*
        $this->mappingdata->get_mapping_data();
        $user_data = $this->session->userdata('user_data');//get session
        //echo "<pre>";print_r($user_data);echo "</pre>";
        if (isset($user_data['CATEGORY_DATA'][$data['category']]) && !empty($user_data['CATEGORY_DATA'][$data['category']])) {
            foreach ($user_data['CATEGORY_DATA'][$data['category']] as $key=>$feed) {
                $url[] = $feed['url'];
            }
            echo $this->get_content($url, '', true);
        } else {
            echo json_encode(array('status'=>false, 'msg'=>'此分類尚無內容', 'next_page'=>''));
        }
		*/
	}
	
	function get_content(&$url,$offset = 0,$jsonflag = false){
		$user_data = $this->session->userdata('user_data');//get session
		$this->load->library('simplepie');
		
		$this->simplepie->set_feed_url($url);
		$this->simplepie->set_cache_duration(999999999);//it's always being updated by the cron job
		$this->simplepie->set_timeout(-1); 
		$this->simplepie->init();
		$this->simplepie->handle_content_type();
		
		$max = $this->simplepie->get_item_quantity();
		
		$length = $this->config->item('rss_feed_count', 'rss');//一次抓幾則回來
		
		$start_offset = $offset*$length;//start index
		$offset++;//讓下一次抓資料用
		//echo "<pre>";print_r($url);echo "</pre>";
		$msg = '';
		
		$counter = 0;
		
		foreach($this->simplepie->get_items($start_offset,$length) as $item){
			if($counter == 0){
				/*
				 * get large ads
				 */ 
				 /*
				$msg .= '<div class="content">'; 
					$msg .= $this->get_ads_large($item->get_title());
				$msg .= '</div>';
				  * */
			}
			
			if((!strpos($item->get_title(), '李宗瑞')) && (!strpos($item->get_title(), '林利霏')) && (!strpos($item->get_content(), '台灣新電影'))){
				$msg .= '<div class="content">';
			$msg .= '<h2 style="position:relative;margin:0;padding:0 0 31px;"><a href="'.$item->get_permalink().'" target="_blank">'.($item->get_title()).'</a>';
			$msg .= '<div class="feed_share" style="display: none;"><a target="_blank"href="https://www.facebook.com/sharer/sharer.php?src=bm&u='.urlencode($item->get_permalink()).'&t='.$item->get_title().'" ><img src="/images/public/facebook_button.png"/></a></div>';
			$msg .= '</h2>';
			
			$matches = array();
			$pattern = '/src=[\'"]?([^\'" >]+)[\'" >]/'; 
			preg_match_all($pattern, $item->get_content(), $matches); 
			
			if(!empty($matches[0])){//this article without images
				$msg .= '<img '.$matches[0][0].' width="200" height="200"/>';	
			}
			else{
				$msg .= '<div class="feed_content">'.$item->get_content().'</div>';
			}
			if(isset($user_data['MAPPING_DATA']['url_mapping_title']['feed:'.$item->get_feed()->subscribe_url()])){
				$msg .= '<div class="feed_title">'.$user_data['MAPPING_DATA']['url_mapping_title']['feed:'.$item->get_feed()->subscribe_url()].'</div>';
			}
			else $msg .= '<div class="feed_title">'.($item->get_feed()->get_title()).'</div>';
			
			$msg .= '</div>';
			if($counter == 5){
				/*
				 * get small ads
				 */ 
				 
				$msg .= '<div class="content">'; 
					$msg .= $this->get_ads_small($item->get_title());
				$msg .= '</div>';
				 
			}
			$counter++;	
			}
		}
		
		
		
		$next_page = '';
		$url_str = '';
		if(is_array($url)){
			foreach($url as $site){
				$url_str .= $site.'|';
			}
			$url_str = substr($url_str,0,-1);
		}
		else{
			$url_str = $url;	
		}
		
		if(($start_offset+$length) < $max){	
			$next_page = '<a href="javascript:;" onclick="getMoreFeed(\''.$url_str.'\',\''.$offset.'\')" id="next">more</a>';
		}
		else{
			$next_page = '';
		}
		/*
		print microtime(true) - $t;
		echo "<br>";exit;
		*/
		//echo 'timestamp:'.date("G:i:s",time());
		if($jsonflag == true){
			return json_encode(array('status'=>true,'msg'=>$msg,'next_page'=>$next_page));
		}
		else return array('status'=>true,'msg'=>$msg,'next_page'=>$next_page);	
	}
	
	function get_ads_large($ads_keywords){
		$data['ads_keywords'] = $ads_keywords;
		return $this->load->view('stareit/large_ads', $data ,true);
	}
	
	function get_ads_small($ads_keywords){
		$data['ads_keywords'] = $ads_keywords;
		return $this->load->view('stareit/small_ads', $data ,true);
	}
	
	function get_ads_search_result(){
		return $this->load->view('stareit/search_result_ads', '' ,true);
	}
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */